package com.xw.bo.ks.util;

import com.xw.bo.ks.entity.base.QueryTime;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 当查询条件有分表的字段，且是between查询字段，应该给到对应的表中取数据就行
 *
 * @author： XW -> ~
 * @create： 2023/11/8 14:36
 */
@Slf4j
public class CustomRangeShardingAlgorithm implements RangeShardingAlgorithm<Integer> {

    @Override
    public Collection<String> doSharding(Collection<String> dataSourceNames, RangeShardingValue<Integer> rangeShardingValue) {

        Set<String> result = new LinkedHashSet<>();

        if (CollectionUtils.isEmpty(dataSourceNames)) {
            log.error("没有分表，请查询好配置");
            return result;
        }

        //between 起始值
        long lower = rangeShardingValue.getValueRange().lowerEndpoint().longValue();
        //between 结束值
        long upper = rangeShardingValue.getValueRange().upperEndpoint().longValue();

        ArrayBlockingQueue<QueryTime> rangeTime = TimeQueueUtil.getMonthTime(lower * 1000, upper * 1000);
        while (!rangeTime.isEmpty()) {
            QueryTime poll = rangeTime.poll();
            String dayTime = DateUtils.formatDateToString(new Date(poll.getStartTime()), DateUtils.DATE_PATTERN_MONTH);
            //循环范围计算分库逻辑
            for (String dataSourceName : dataSourceNames) {
                if (dataSourceName.endsWith(dayTime)) {
                    result.add(dataSourceName);
                }
            }
        }

        // 没有命中分片，就随机一个表给他，防止出现异常
        if (CollectionUtils.isEmpty(result)) {
            for (String dataSourceName : dataSourceNames) {
                log.error("请注意，来了一个没有分片的结果，随机的库为：{},lower={},upper={}","ks_open_order_cursor_lists2023_08",lower,upper);
                result.add("ks_open_order_cursor_lists2023_08");
                break;
            }
        }
        return result;
    }


}
